#import "ToDoManager.h"

static ToDoManager *toDoManagerInstance;

@implementation ToDoManager

//singleton methode!
+ (ToDoManager *)sharedToDoManager
{
	if (!toDoManagerInstance) {
		toDoManagerInstance = [[ToDoManager alloc] init];
	}
	
	return toDoManagerInstance;
}

- (void)updateIconInfo
{
	[td setApplicationBadge: [NSString stringWithFormat: @"1"]];
}

- (NSMutableArray *)todos
{
	return todos;
}

- (void)setTodos:(NSMutableArray *)myToDos
{
	myToDos = [myToDos mutableCopy];
	[todos release];
	todos = myToDos;
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}

- (id)init
{
	self = [super init];

	toDoManagerInstance = self;
		
	todos = [[NSMutableArray alloc] init];
	possibleGroups = [[NSMutableArray alloc] init];
	preferences = [[NSMutableDictionary alloc] init];
	
	return self;
}

-(void)setPref:(NSString *)myKey withValue:(NSString *)myValue
{
	[preferences setObject:myValue forKey:myKey ];
}

-(NSString *)getPref:(NSString *)myKey
{
	if([preferences objectForKey:myKey]) {
		return [preferences objectForKey:myKey];
	}
	else {
		return @"";
	}
}



- (void)deleteAllOldToDos
{
	int i=0;
	for(i=0;i < [todos count]; i++) {
		// go throught all todos
		if([[todos objectAtIndex:i] getCheckedDate]) {
			int dayChanges = 0;
			if([[self getPref:@"deleteAfter"] isEqualToString:@"1 Day"]) {
				dayChanges = 1;
			}
			if([[self getPref:@"deleteAfter"] isEqualToString:@"2 Days"]) {
				dayChanges = 2;
			}
			if([[self getPref:@"deleteAfter"] isEqualToString:@"5 Days"]) {
				dayChanges = 5;
			}
			if([[self getPref:@"deleteAfter"] isEqualToString:@"Never"]) {
				dayChanges = 0;
			
			}
			
			
			
			if(dayChanges != 0) {
				NSCalendarDate* checkDate = [[NSCalendarDate calendarDate] dateByAddingYears:0 months:0 days:-dayChanges hours:0 minutes:0 seconds:0];
				if(![[[[todos objectAtIndex:i] getCheckedDate] earlierDate:checkDate] isEqual:checkDate]) {
					// HIDE TODO
					[self removeToDo:i];
				}
			}
		}
	}
}

- (int)getGroupNumberBySplitsFromToDo:(int)myToDo
{
	int i;
	
	for(i=0;i<[groupSplits count];i++) {
		if([[groupSplits objectAtIndex:i] intValue] >= myToDo ) {
			// got the group
			return [[groupSplits objectAtIndex:i] intValue];
			break;
		}
	}
	return nil;
}


- (void)fixOrder
{

	int i=0;
	NSMutableArray *myGroupArray;
	myGroupArray = [[NSMutableArray alloc] init];
	int cnt=0;
	for(i=0;i < [todos count]; i++) {
		// go throught all todos
		[[todos objectAtIndex:cnt] setPosition:i];
	}
}

- (int)getTodoCountInGroup:(int)myGroup
{
	int i=0;
	int cnt=0;
	for(i=0;i < [todos count]; i++) {
		// go throught all todos
		if([[todos objectAtIndex:i] getGroup] == myGroup) {
			cnt++;
		}
	}
	return cnt;
}


-(void)orderTodosByGroup
{
	NSMutableArray *myGroup;
	NSMutableArray *myGroup2;
	NSMutableArray *myAllGroups;
	NSNumber *myNum;
	
	myAllGroups = [[NSMutableArray alloc] init];
	groupSplits = [[NSMutableArray alloc] init];
	int i;
	int cnt=0;
	myNum = [[NSNumber alloc] initWithInt:cnt];
	[groupSplits addObject:myNum];
	for(i=0;i<[[self getPossibleGroups] count];i++) {
		int ii=0;
		myGroup = [[NSMutableArray alloc] init];
		
		for(ii=0;ii < [todos count]; ii++) {
			// go throught all todos
			if([[todos objectAtIndex:ii] getGroup] == i) {
				cnt++;
				[myGroup addObject: [todos objectAtIndex:ii]];
			}
		}
		
		// GOT ALL TODOS IN SAME GROUP
		// NOW SORT BY WHAT EVER
		if([[self getPref:@"orderBy"] isEqualToString:@"Due Date"]) {
			[myGroup sortUsingSelector:@selector(compareDueDate:)];
		}
		else if([[self getPref:@"orderBy"] isEqualToString:@"Priority"]) {
			[myGroup sortUsingSelector:@selector(comparePriority:)];
		}
		else {
			[myGroup sortUsingSelector:@selector(compareAlpha:)];
		}
			
		myNum = [[NSNumber alloc] initWithInt:cnt];
		[groupSplits addObject:myNum];
		[myAllGroups addObjectsFromArray:myGroup];
	}
	
	todos = myAllGroups;
}

- (int)numberOfTodos
{
	return [todos count];
}



- (int)numberOfOpenTodos
{
	int cnt=0;
	int i;
	for(i=0;i < [todos count]; i++) {
		if([[todos objectAtIndex:i] getDone] != 1) {
			cnt++;
		}
	}
	
	return cnt;
}


- (int)addToDo:(ToDo *)myToDo
{
	
	[todos addObject:[myToDo copy]];
	[self fixOrder];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
	// save data now!
	[self writeToFile];
	
	return [todos count];
}

- (void)removeToDo:(int)myToDo
{
	[todos removeObjectAtIndex:myToDo];
	[self fixOrder];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}

- (void)setCurrentFile:(NSString *)myFile
{
	currentFile = myFile;
}
- (void)setCurrentGroupFile:(NSString *)myFile
{
	currentGroupFile = myFile;
}
- (void)setCurrentPreferenceFile:(NSString *)myFile
{
	currentPreferenceFile = myFile;
}

- (void)setCurrentToDo:(int)myToDo
{
	currentToDo = myToDo;
}

- (NSString *)getCurrentToDoDescription
{
	return [[todos objectAtIndex:currentToDo] getDescription];
}

- (int)getCurrentToDo
{
	return currentToDo;
}

- (int)getNextUnnamed
{
	int cnt=0;
	int i;
	for(i=0;i < [todos count]; i++) {
		if([[[todos objectAtIndex:i] getDescription] isEqualToString:@""]) {
			return i;
		}
	}
}

- (int)getNextUnnamedGroup
{
	int cnt=0;
	int i;
	for(i=0;i < [possibleGroups count]; i++) {
		if([[possibleGroups objectAtIndex:i] isEqualToString:@""]) {
			return i;
		}
	}
}


- (void)setDescription:(NSString *)myDescription forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setDescription:myDescription];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}

- (void)setDone:(int)myDoneState forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setDone:myDoneState];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}

- (void)swapDoneforToDo:(int)myToDo
{
	if([[todos objectAtIndex:myToDo] getDone] == YES) {
		[[todos objectAtIndex:myToDo] setDone:NO];
		[[todos objectAtIndex:myToDo] setUnchecked];
	}
	else {
		[[todos objectAtIndex:myToDo] setDone:YES];
		[[todos objectAtIndex:myToDo] setCheckedNow];
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}

- (int)getDaysChecked:(int)myToDo
{
	return 1;
}

- (NSCalendarDate *)setDueDate:(NSCalendarDate *)myDate forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setDueDate:myDate];
}
- (NSCalendarDate *)getDueDateFromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getDueDate];
}
- (NSCalendarDate *)setCreationDate:(NSCalendarDate *)myDate forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setCreationDate:myDate];
}
- (NSCalendarDate *)getCreationDateFromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getCreationDate];
}

- (NSString *)getDescriptionFromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getDescription];
}

- (int)getGroupNumberFromToDo:(int)myToDo
{
	
	return [[todos objectAtIndex:myToDo] getGroup];
}
- (NSString *)getGroupNameFromToDo:(int)myToDo
{
	if([ possibleGroups count ] >= [[todos objectAtIndex:myToDo] getGroup]) {
		return [ possibleGroups objectAtIndex:[[todos objectAtIndex:myToDo] getGroup] ];
	}
	else {
		return @"unknown";
	}
}

- (void)setGroup:(int)myGroup forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setGroup:myGroup];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}
- (void)setPosition:(int)myPosition forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setPosition:myPosition];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}
- (int)getPositionFromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getPosition];
}
- (void)setPriority:(int)myPrio forToDo:(int)myToDo
{
	[[todos objectAtIndex:myToDo] setPriority:myPrio];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
}
- (int)getPriorityfromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getPriority];
}


- (BOOL)isToDoExpired:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] isExpired];
}

- (int)getDoneFromToDo:(int)myToDo
{
	return [[todos objectAtIndex:myToDo] getDone];
}

- (NSMutableArray *)getPossibleGroups
{
	return possibleGroups;
}
- (int) getCurrentGroup
{
	return currentGroup;
}
- (NSString *) getCurrentGroupName
{
	return [possibleGroups objectAtIndex:currentGroup];
}
- (void) setCurrentGroup:(int)myGroup
{
	currentGroup = myGroup;
}

- (void)removeCurrentGroup
{

	
	// first move all todo's
	int i;
	for(i=0;i < [todos count]; i++) {
		// go thought all todos
		if([[todos objectAtIndex:i] getGroup] == currentGroup) {
			// set the todo to the first group!
			[self setGroup:0 forToDo:i];
		}
	}
	
	[possibleGroups removeObjectAtIndex:currentGroup];
	if([possibleGroups count] <= 0) {
		// oho! .. no groups... add one
		[possibleGroups addObject:@"default"];
	}
		
	[self orderTodosByGroup];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoDidChangeNotification" object:self];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoGroupsChangeNotification" object:self];
}

- (NSMutableArray *)getGroupSplits
{
	return groupSplits;
}

- (int)addGroup:(NSString *)groupName
{
	[possibleGroups addObject:groupName];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoGroupsChangeNotification" object:self];
	
	return [possibleGroups count];
}
- (void)setGroup:(NSString *)myGroupName atIndex:(int)myIndex
{
	[possibleGroups setObject:myGroupName atIndex:myIndex];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"ToDoGroupsChangeNotification" object:self];
}

- (void)writePreferences
{
	[NSKeyedArchiver archiveRootObject:preferences toFile:currentPreferenceFile];
}
- (void)loadPreferences
{
	if ([[NSFileManager defaultManager] fileExistsAtPath:currentPreferenceFile]) {
		NSMutableDictionary *tempPreferences = [NSKeyedUnarchiver unarchiveObjectWithFile:currentPreferenceFile];
		tempPreferences = [tempPreferences mutableCopy];
		[preferences release];
		preferences = tempPreferences;
	}
}


- (void)writeToFile
{
	[NSKeyedArchiver archiveRootObject:todos toFile:currentFile];
	[NSKeyedArchiver archiveRootObject:possibleGroups toFile:currentGroupFile];
}

- (void)loadFile
{
	// load groups
	if ([[NSFileManager defaultManager] fileExistsAtPath:currentGroupFile]) {
		NSMutableArray *tempGroups = [NSKeyedUnarchiver unarchiveObjectWithFile:currentGroupFile];
		if ([tempGroups count] > 0) {
			tempGroups = [tempGroups mutableCopy];
			[possibleGroups release];
			possibleGroups = tempGroups;
		}
	}
	else {
		// create so initional groups
		[possibleGroups addObject:@"work"];
		[possibleGroups addObject:@"private"];
		[possibleGroups addObject:@"family"];
	}
	
	// check if a todo break the range!
	int i;
	for(i=0;i < [todos count]; i++) {
		// go thought all todos
		if([[todos objectAtIndex:i] getGroup] > [possibleGroups count]) {
			// set the todo to the first group!
			[self setGroup:0 forToDo:i];
		}
	}
	
	//load todos
	if ([[NSFileManager defaultManager] fileExistsAtPath:currentFile]) {
		NSMutableArray *temp = [NSKeyedUnarchiver unarchiveObjectWithFile:currentFile];
		if ([temp count] > 0) {
			[self setTodos:temp];
		}
	}
	else {
		ToDo *myToDo = [[ToDo alloc] init];
		int toDoNum = [self addToDo:myToDo];
		[self setDescription:@"help beta-test, report bugs" forToDo:toDoNum-1];
	}
}


@end